ARG NODE_VERSION=22.17
ARG DOTNET_VERSION=10.0-preview-alpine

FROM mcr.microsoft.com/dotnet/aspnet:${DOTNET_VERSION} AS base
USER app
WORKDIR /app

FROM node:${NODE_VERSION}-alpine AS node-base

ARG NPM_REGISTRY=https://registry.npmjs.org/
# ARG NPM_REGISTRY=https://registry.npmmirror.com/

ENV COREPACK_NPM_REGISTRY=${NPM_REGISTRY}
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"

RUN corepack enable

# 还原NPM包
FROM node-base AS node-install

COPY ["./frontend/package.json", "./frontend/pnpm-lock.yaml", "./frontend/tsconfig.json", "./frontend/index.html", "./frontend/vite.config.ts", "/src/"]

WORKDIR /src
RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm install --frozen-lockfile

FROM node-install AS node-build
COPY ["./frontend", "."]

RUN pnpm run build

FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION} AS dotnet-restore
ARG BUILD_CONFIGURATION=${BUILD_CONFIGURATION:-Release}

COPY ["./Certs.Apis/Certs.Apis.csproj", "/src/Certs.Apis/"]
COPY ["./ProxyServer.Web/ProxyServer.Web.csproj", "/src/ProxyServer.Web/"]
COPY ["./ProxyServer.Sqlite/ProxyServer.Sqlite.csproj", "/src/ProxyServer.Sqlite/"]
COPY ["./ProxyServer.Npgsql/ProxyServer.Npgsql.csproj", "/src/ProxyServer.Npgsql/"]
COPY ["./ProxyServer.CommandLine/ProxyServer.CommandLine.csproj", "/src/ProxyServer.CommandLine/"]
COPY ["./Directory.Packages.props", "/src/"]
COPY ["./nuget.config", "/src/"]

WORKDIR /src
RUN --mount=type=cache,id=nuget,target=/root/.nuget/packages dotnet restore "./ProxyServer.CommandLine/ProxyServer.CommandLine.csproj"

FROM dotnet-restore AS dotnet-build

COPY ["./Certs.Apis", "./Certs.Apis"]
COPY ["./ProxyServer.Web", "./ProxyServer.Web"]
COPY ["./ProxyServer.Npgsql", "./ProxyServer.Npgsql"]
COPY ["./ProxyServer.Sqlite", "./ProxyServer.Sqlite"]
COPY ["./ProxyServer.CommandLine", "./ProxyServer.CommandLine"]

RUN rm -rf "/src/ProxyServer/wwwroot"

RUN --mount=type=cache,id=nuget,target=/root/.nuget/packages dotnet build "./ProxyServer.CommandLine/ProxyServer.CommandLine.csproj"

FROM dotnet-build AS publish
ARG BUILD_CONFIGURATION=Release
RUN --mount=type=cache,id=nuget,target=/root/.nuget/packages dotnet publish "./ProxyServer.CommandLine/ProxyServer.CommandLine.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
COPY --from=node-build ["/src/dist/index.html", "/src/dist/assets", "/src/dist/", "./wwwroot/"]
ENTRYPOINT ["dotnet", "ProxyServer.Web.dll"]
